import os, time
from Tkinter import *

class main():
    def __init__(self,parent,root):
        
        self.root = root
        self.root.title('Search Inventory by Keyword')
        self.dh = parent.dh
        self.boothPath = parent.boothPath
        self.parent = parent
        
        cons_nums = []
        for dirs in os.listdir(self.boothPath):
            cons_nums.append(int(dirs))
            
        max_assigned = max(cons_nums)
        self.keyword = StringVar()

        self.status = StringVar()
        self.status.set('Enter consignor by name or number and click Search to get started')
        
        kwLabel = Label(self.root,text= 'Keyword : ').grid(row=0,column=0,sticky=W)
        kwEntry = Entry(self.root,textvariable=self.keyword,width=40)
        kwEntry.grid(row=0,column=1,sticky=W)
        kwEntry.bind('<Return>',self.searchByKw)
        kwEntry.bind('<KP_Enter>',self.searchByKw)
        kwEntry.focus()

        findByKw = Button(self.root, text='Search',command=self.searchByKw, width=10).grid(row=0,column=2)
        self.resultsBox = Listbox(self.root,width=80,height=30)
        self.resultsBox.grid(row=1,column=0,columnspan=3)
        self.resultsBox.bind('<Double-Button-1>',self.addToSale)
        
        doneButton = Button(self.root,text=' Done ', command=self.finalize, width=10).grid(row=2,column=2,sticky=E)
        #print type(self.resultsBox)

            
    def searchByKw(self,event=None):
        kw = self.keyword.get()
        for key in self.dh.cons_dict.keys():
            for item_key in self.dh.cons_dict[key].item_dict.keys():
                if kw.lower() in self.dh.cons_dict[key].item_dict[item_key].description.lower():
                    item = self.dh.cons_dict[key].item_dict[item_key]
                    insText = '%s  %s   $%s   Owner: %s Description: %s' % (item.owner_number, item.item_number, item.sale_price, item.owner, item.description)
                    self.resultsBox.insert(END, insText)
                    
    def addToSale(self,event=None):   
        anchor = self.resultsBox.curselection()
        data = self.resultsBox.get(anchor)
        data = data.split()
        booth,item,price = data[0],data[1],data[2].strip('$')
        price = int(float(price)*100)
        lkpItem = '%s %s %s' % (booth, item, price)
        self.parent.readBarcode.set(lkpItem)
        self.parent.lookupItem()
    
    def finalize(self):

        self.root.destroy()
            
        

def start(parent,root):
        
    ins = main(parent,root)
